// pages/guest/store/order/order.js
const db=wx.cloud.database();
var app = getApp()
var util = require("../../../../utils/util.js")
const _ = db.command

var moveFlag = true;// 判断执行滑动事件
var startX, endX;  //接触开始和结束x坐标
var moveFlag = true;//确保移动方向为首次

Page({

  /**
   * 页面的初始数据
   */
  data: {
    active:'pending',
    cartsDate:null,
    checkobj:{},
    numobj:{},
    priceobj:{},
    outcheckbj:{
      Tuina:false,
      Medic:false,
      Sideline:false
    },
    orderHidden:false,
    allbechecked:'全选',
    checked:false,
    totalPrice:0,
    vipTip:"开通会员可享9折优惠",
    isvip:false,
    userBalance:0,
    currentClick: 1,   
    currentSelected:'pending',
    //待评价
    UnEvaluateData:null,
    activeNames: ['1'],
    all_activeNames:['1'],
    allEvaluateData:null
  },
  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  allonChange(event) {
    this.setData({
      all_activeNames: event.detail,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
let that=this
that.getuserCarts()
 that.isVip()
  },

  isVip:function(){
    let that = this
    db.collection('userlogin').where({
      identity:'user',
      userPhone:app.userDate.userInfo.userPhone
    }).get().then(res=>{
        console.log(res)
        if(res.data[0].clubCard!=''){
            that.setData({
              isvip:true
            })
        }
        that.setData({
          userBalance:res.data[0].userBalance
        })
    })
  },


  getuserCarts:function(){
    wx.showLoading({
      title: '正在加载...',
    })
    let that = this
    that.setData({
      checkobj:{},
      numobj:{},
      priceobj:{},
    })
      wx.cloud.callFunction({
        name:'getchartsData',
        data:{
          userid:app.userDate.userInfo.userPhone
        }
      }).then(res=>{
        console.log(res)
        that.setData({
          cartsDate:res.result
        })
        res.result.Tuinadata.list.forEach((value, index, arr) => {
            that.data.checkobj[value.TuinaID]=false
            that.data.numobj[value.TuinaID]=1
            that.data.priceobj[value.TuinaID] = value.TuinaPrice
        });
          res.result.Meddata.list.forEach((value, index, arr) => {
            that.data.checkobj[value.MedicID]=false
            that.data.numobj[value.MedicID]=1
            that.data.priceobj[value.MedicID] = value.MedicPrice
        });
          res.result.Sidedata.list.forEach((value, index, arr) => {
            that.data.checkobj[value.SidelineID]=false
            that.data.numobj[value.SidelineID]=1
            that.data.priceobj[value.SidelineID] = value.SidelinePrice
        });
        console.log(that.data.checkobj,that.data.numobj,that.data.priceobj)
        that.setData({
          numobj:that.data.numobj
        })
        wx.hideLoading()
        // console.log(that.data.cartsDate.Tuinadata)
      })
  },
  checkboxChange:function(e){
    console.log(e)
  },
  onecheckChange:function(e){
      // console.log(e.currentTarget.dataset.id)
      // console.log(e.currentTarget.dataset.type)

      let that =this
      let id = e.currentTarget.dataset.id
      let type =e.currentTarget.dataset.type
      let a = that.data.checkobj[id]
      // console.log(a)
      that.data.checkobj[id] = !a
      // console.log(that.data.checkobj)
        for(let key  in that.data.checkobj){
            // console.log(key,that.data.checkobj[key])
            if(key.slice(0,1)==type.slice(0,1)){
              if(!that.data.checkobj[key]){
                // console.log("进入")
                that.data.outcheckbj[''+type] = false
                that.setData({
                  outcheckbj:that.data.outcheckbj,
                  checkobj:that.data.checkobj
                })
                that.computePrice()
                  return
              }
            }
      }
      that.data.outcheckbj[''+type] = true
      that.setData({
        outcheckbj:that.data.outcheckbj,
        checkobj:that.data.checkobj
      })
      that.computePrice()
      // console.log(that.data.outcheckbj)
  },
  allbechecked:function(){
    let that = this
    if(!that.data.checked){
      for(let key  in that.data.checkobj){
          that.data.checkobj[key]=true
      }
      for(let key in that.data.outcheckbj){
        that.data.outcheckbj[key]=true
      }
      that.setData({
        checked:true,
        allbechecked:'取消全选',
        checkobj:that.data.checkobj,
        outcheckbj:that.data.outcheckbj
      })
      that.computePrice()
    }else{
      for(let key  in that.data.checkobj){
        that.data.checkobj[key]=false
    }
    for(let key in that.data.outcheckbj){
      that.data.outcheckbj[key]=false
    }
    that.setData({
      checked:false,
      allbechecked:'全选',
      checkobj:that.data.checkobj,
      outcheckbj:that.data.outcheckbj
    })
    that.computePrice()
    }
  },

  outCheckchange:function(e){
    let type =e.currentTarget.dataset.type
    let that = this
    // console.log(type)
    // console.log(that.data.outcheckbj[''+type])
    let value = !(that.data.outcheckbj[''+type])
    that.data.outcheckbj[''+type] = value
    // console.log(that.data.outcheckbj)
    if(value) {
      for(let key  in that.data.checkobj){
          if(key.slice(0,1)==type.slice(0,1)){
            that.data.checkobj[key] = true
          }
      }
      that.setData({
        checkobj:that.data.checkobj
      })
      that.computePrice()
      // console.log(that.data.checkobj)
    }else{
      for(let key  in that.data.checkobj){
        if(key.slice(0,1)==type.slice(0,1)){
          that.data.checkobj[key] = false
        }
      }
      that.setData({
        checkobj:that.data.checkobj
      })
      that.computePrice()
    }
  },
  stepperonChange:function(e){
  console.log(e)
     let value = e.detail
     let id = e.currentTarget.dataset.id
     let that = this
     that.data.numobj[id]=value
     that.setData({
       numobj:that.data.numobj
     })
     that.computePrice()
  },

 computePrice:function(){
   let that = this
   let price = 0
  for(let key  in that.data.checkobj){
        if(that.data.checkobj[key]){
          price+=(that.data.priceobj[key])*(that.data.numobj[key])
        }
  }
  console.log(price)
  if(that.data.isvip){
    that.setData({
      vipTip:"您已享受九折会员价",
      totalPrice:price*100*0.9
    })
  }else{
    that.setData({
      vipTip:"开通会员可享9折优惠",
      totalPrice:price*100
    })
  }
 },
 onClickButton:function(res){
   let that = this
   let _balance = that.data.userBalance
   let _totalPrice = that.data.totalPrice/100
   console.log(_totalPrice,_balance)
     if(_balance<_totalPrice){
      wx.showModal({
        title: '提示',
        content: '你的余额不足，请前往前台充值!'
        })
     }else{
       wx.showLoading({
         title: '正在扣除余额...',
       })
        wx.cloud.callFunction({
          name:'update',
          data:{
            phone:app.userDate.userInfo.userPhone,
            balance:_balance-_totalPrice
          }
        }).then(res=>{
           wx.hideLoading()
          if(res.result.errMsg=="collection.update:ok"){
              that.writeOrdertoDB()
              wx.showToast({
                title: '支付成功!',
                icon:'success'
              })
              that.setData({
                currentClick: 2,
                currentSelected:'pendEvalue',
                active:'pendEvalue',
                orderHidden:true
              })
          }else{
            wx.showToast({
              title: '支付失败',
              icon:'/images/icon/defeat.png'
            })
          }
        })
     }
 },

 removeFromCarts:function(e){
   let _id = e.currentTarget.dataset.id
   let that = this
   let _user =app.userDate.userInfo.userPhone
   wx.showModal({
    title: '提示',
    content: '确定从购物车中删除该商品？',
    success (res) {
    if (res.confirm) {
      that.deleteCartsDB(_id,_user)
    } else if (res.cancel) {
        console.log("点击取消")
    }
    }
    })
 },
 writeOrdertoDB:function(){
let that = this
let _userID =app.userDate.userInfo.userPhone
  for(let key  in that.data.checkobj){
    wx.showLoading({
      title: '正在生成订单...'
    })
    if(that.data.checkobj[key]){
      let price = that.data.priceobj[key]
      if(that.data.isvip){
          price = price*0.9
      }
      // 添加订单
      db.collection('OrderData').add({
        data:{
          Isevaluated:false,
          OrderData: util.formatDateTime(new Date()),
          OrderID:key,
          OrderNum:that.data.numobj[key],
          TransactionAmount:price,
          UserID:_userID,
          isweihu:false
        }
      }).then(res=>{
       console.log("加入订单",res)
      })

      //商品数据库更新
      if(key.slice(0,1)=='T'){
        console.log("tuina")
      wx.cloud.callFunction({
        name:'updateTuinaData',
        data:{
          TID:key,
          tip:'user',
        }
      }).then(res=>{
        console.log(res)
        console.log("推拿更新成功")
      })
    }else if(key.slice(0,1)=='M'){
      wx.cloud.callFunction({
        name:'updateMedicineData',
        data:{
          MID:key,
          tip:'user',
          num:that.data.numobj[key]
        }
      }).then(res=>{
        console.log("药品更新成功")
      })
    }else{
      wx.cloud.callFunction({
        name:'updateSidelineData',
        data:{
          SID:key,
          tip:'user',
        }
      }).then(res=>{
        console.log(res)
        console.log("副业更新成功")
      })
    }
    wx.hideLoading()
      //删除购物车
      that.deleteCartsDB(key,_userID)
    }
}
 },

onClick(ev){
  console.log(ev);
  let that = this
  let _name = ev.detail.name
  if(_name=='pending'){
    that.setData({
      currentClick: 1,
      currentSelected:'pending',
      active:'pending',
      orderHidden:false
    });
    that.getuserCarts()
     that.isVip()
  }else if(_name=='pendEvalue'){
    that.setData({
      currentClick: 2,
      currentSelected:'pendEvalue',
      active:'pendEvalue',
      orderHidden:true
    });
    that.getUnEvaluateOrder()
  }else{
    that.setData({
      currentClick: 3,
      currentSelected:'allOrder',
      active:'allOrder',
      orderHidden:true
    });
    that.getallEvaluateOrder()
  }
},

 deleteCartsDB:function(_id,_user){
   let that = this
  console.log("删除购物车")
  wx.cloud.callFunction({
    name:'deleteUserCarts',
    data:{
      id:_id,
      user:_user
    }
  }).then(res=>{
    console.log(res)
    if(res.errMsg=="cloud.callFunction:ok"){
      that.getuserCarts()
      wx.showToast({
        title: '删除成功!',
        icon:'success'
      })
    }else{
      wx.showToast({
        title: '删除失败，请重试!',
        icon:'/images/icon/defeat.png'
      })
    }
  })
 },

   //屏幕滑动事件
  //触摸开始
  touchStart: function (e) {
    // console.log("触摸开始")
    startX = e.touches[0].pageX;
    moveFlag = true;
  },


  touchMove: function (e) {
    // console.log("移动")
    var that = this
    endX = e.touches[0].pageX;
    if (moveFlag) {
      if (endX - startX > 100) {
        // console.log("左滑");
        that.moveright();
        moveFlag = false;
      }
      if (startX - endX > 100) {
        // console.log("右滑");
        that.moveleft();
        moveFlag = false;
      }
    }
  },

  touchEnd: function (e) {
    // console.log("触摸结束")
    moveFlag = true; // 回复滑动事件 
  },

  moveleft() {
    var that = this;
    let currentPage = that.data.currentClick
    if (currentPage >= 3) {
      wx.showToast({
        title: '滑动到最右了哦~',
        icon: "none"
      })
    } else {
      currentPage += 1
      console.log(currentPage)
      if(currentPage==1){
        that.setData({
          currentClick: currentPage,
          currentSelected:'pending',
          active:'pending',
          orderHidden:false
          // listData:[]//清空list数组，避免渲染先出现格式后显示数据
        });
        that.getuserCarts()
         that.isVip()
      }else if(currentPage==2){
        that.setData({
          currentClick: currentPage,
          currentSelected:'pendEvalue',
          active:'pendEvalue',
          orderHidden:true
          // listData:[]//清空list数组，避免渲染先出现格式后显示数据
        });
        that.getUnEvaluateOrder()
      }else{
        that.setData({
          currentClick: currentPage,
          currentSelected:'allOrder',
          active:'allOrder',
          orderHidden:true
          // listData:[]//清空list数组，避免渲染先出现格式后显示数据
        });
        that.getallEvaluateOrder()
      }
    }
  },
  moveright() {
    var that = this;
    let currentPage = that.data.currentClick
    if (currentPage <= 1) {
      wx.showToast({
        title: '滑动到最左了哦~',
        icon: "none"
      })
    } else {
      currentPage -= 1
     
console.log(currentPage)
      if(currentPage==1){
        that.setData({
          currentClick: currentPage,
          currentSelected:'TuinaData',
          active:'pending',
          orderHidden:false
       
        });
        that.getuserCarts()
        that.isVip()
      }else if(currentPage==2){
        that.setData({
          currentClick: currentPage,
          currentSelected:'pendEvalue',
          active:'pendEvalue',
          orderHidden:true
        
        });
      that.getUnEvaluateOrder()
      }else{
        that.setData({
          currentClick: currentPage,
          currentSelected:'SidelineData',
          active:'allOrder',
          orderHidden:true
        });
          that.getallEvaluateOrder()
      }
    }
  },

/**********************下面是待评价相关方法******************************************** */

  getUnEvaluateOrder:function(e){
    let that = this
    wx.showLoading()
     wx.cloud.callFunction({
       name:'getUserOrder',
       data:{
          id:'pendEvalue',
          userid:app.userDate.userInfo.userPhone
       }
     }).then(res=>{
       console.log(res)
       that.setData({
         UnEvaluateData:res.result
       })
       wx.hideLoading()
     })
  },
  getallEvaluateOrder:function(e){
    let that = this
    wx.showLoading()
     wx.cloud.callFunction({
       name:'getUserOrder',
       data:{
          id:'allOrder',
          userid:app.userDate.userInfo.userPhone
       }
     }).then(res=>{
       console.log(res)
       that.setData({
         allEvaluateData:res.result
       })
       wx.hideLoading()
     })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  clickEvaluate:function(e){
      console.log(e.target.dataset.id)
      let id = e.target.dataset.id
      let sid = e.target.dataset.sid
      wx.navigateTo({
        url: './evaluate/evaluate?id='+id+'&sid='+sid,
      })
  },
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})